package org.lemon.transport.coap.server.service.callback;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.californium.core.coap.CoAP;
import org.eclipse.californium.core.server.resources.CoapExchange;
import org.lemon.transport.context.auth.ValidateDeviceCredentialsResponse;
import org.lemon.transport.context.data.device.DeviceProfile;
import org.lemon.transport.context.service.TransportAuthServiceCallback;

import java.util.function.Consumer;

@Slf4j
public class CoapDeviceAuthCallback implements TransportAuthServiceCallback<ValidateDeviceCredentialsResponse> {

    private final CoapExchange exchange;
    private final Consumer<ValidateDeviceCredentialsResponse> onSuccess;

    public CoapDeviceAuthCallback(CoapExchange exchange, Consumer<ValidateDeviceCredentialsResponse> onSuccess) {
        this.exchange = exchange;
        this.onSuccess = onSuccess;
    }

    @Override
    public void onSuccess(ValidateDeviceCredentialsResponse msg) {
        DeviceProfile deviceProfile = msg.getDeviceProfile();
        if (msg.hasDeviceInfo() && deviceProfile != null) {
            onSuccess.accept(msg);
        } else {
            exchange.respond(CoAP.ResponseCode.UNAUTHORIZED);
        }
    }

    @Override
    public void onError(Throwable e) {
        log.warn("Failed to process request", e);
        exchange.respond(CoAP.ResponseCode.INTERNAL_SERVER_ERROR);
    }
}
